package com.atguigu.atcrowdfunding.controller;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.atguigu.atcrowdfunding.bean.TMenu;
import com.atguigu.atcrowdfunding.bean.TPermission;
import com.atguigu.atcrowdfunding.service.TMenuService;
import com.atguigu.atcrowdfunding.service.TPermissionService;

@Controller
public class TMenuController {
	
	@Autowired
	TMenuService menuService;
	
	@Autowired
	TPermissionService PermissionService;
	
	@RequestMapping("/menu/index")
	public String index() {
		return "/menu/index";
	}
	
	@RequestMapping("/menu/loadTree")
	@ResponseBody
	public List<TMenu> loadTree() {
		List<TMenu> list = menuService.listAllMenuOnTree();
		return list;
	}
	
	@RequestMapping("/menu/doAdd")
	@ResponseBody
	public String doAdd(TMenu menu) {
		try {
			menuService.saveMenu(menu);
		} catch (Exception e) {
			return "error";
		}
		return "ok";
	}
	
	@RequestMapping("/menu/getMenuById")
	@ResponseBody
	public TMenu getMenuById(Integer id) {
		TMenu menu = menuService.getMenuById(id);
		return menu;
	}
	
	@RequestMapping("/menu/doUpdate")
	@ResponseBody
	public String doUpdate(TMenu menu) {
		try {
			menuService.updateMenu(menu);
		} catch (Exception e) {
			return "error";
		}
		return "ok";
	}
	
	@RequestMapping("/menu/doDelete")
	@ResponseBody
	public String doDelete(Integer id) {
		try {
			menuService.deleteMenu(id);
		} catch (Exception e) {
			return "error";
		}
		return "ok";
	}
	
	@RequestMapping("/menu/assignPermissionToMenu")
	@ResponseBody
	public String assignPermissionToMenu(Integer mid, Integer[] perIds) {
		try {
			List<Integer> perIdArray = new ArrayList<Integer>();
			Collections.addAll(perIdArray,perIds);
			PermissionService.assignPermissionToMenu(mid, perIdArray);
		} catch (Exception e) {
			return "error";
		}
		return "ok";
	}
	
	@RequestMapping("/menu/menuPermission")
	@ResponseBody
	public List<TPermission> menuPermission(Integer menuid) {
		List<TPermission> list = null;
		try {
			list = PermissionService.getPermissionByMenuid(menuid);
		} catch (Exception e) {
			return null;
		}
		return list;
	}
}
